package cn.net.pojo;

import cn.net.httpclient.HttpClientSystem;
import cn.net.model.*;
import cn.net.netmodel.RequestParams;
import cn.net.util.ParamsUtil;
import com.google.common.collect.Lists;
import org.apache.http.client.methods.HttpGet;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.UUID;

/**
 * Created by Administrator on 2017/8/23.
 */
@Component
public class _5J {

    @Autowired
    private HttpClientSystem client;

    public CacheDataObject _5JSearch(RequestParams params) {
        CacheDataObject cdo = _5JSearch(client, params.getDep(), params.getArr(), params.getTime(), params.getCount());
        return cdo;
    }

    public CacheDataObject _5JSearch(HttpClientSystem client, String dep, String arr, String time, String count) {
        HttpGet get = new HttpGet();
        get.setURI(URI.create("https://beta.cebupacificair.com/Flight/InternalSelect?o1=" + dep + "&d1=" + arr + "&o2=&d2=&dd1=" + time + "&ADT=" + count + "&CHD=0&INF=0&s=true&mon=true"));
        get.setHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        get.setHeader("referer", "https://beta.cebupacificair.com/");
        get.setHeader("upgrade-insecure-requests", "1");
        get.setHeader("user-agent", ParamsUtil.USER_AGENT_CHROME);
        String string = client.get(get);
        System.out.println(get.getURI());
        if (string == null)
            return null;
 
        LinkedList<Routing> rts = Lists.newLinkedList();

        Document document = Jsoup.parse(string);

        Elements tbodys = document.getElementsByTag("tbody");
        if (tbodys == null || tbodys.size() <= 1)
            return null;
        Element tbody = tbodys.get(1);

        Elements trs = tbody.children();// 所有航线
        for (Element t : trs) {
            if (t.text().contains("Sorry,")) {
                CacheDataObject cdo = new CacheDataObject();
                ReturnObject ro = new ReturnObject();
                ro.setRoutings(rts);
                ro.setStatus(0);
                ro.setMsg("sorry the day no data");
                cdo.setDbFlag(0);
                cdo.setFlag("true");
                cdo.setReturnObject(ro);
                cdo.setTimeNow(DateTime.now().toString());
                return cdo;
            }

            if (!t.attr("class").contains("faretable-row"))
                continue;

            Element input = t.getElementsByTag("input").get(0);

            String value = input.attr("value");

            String ss = value.split("\\|")[1];
            String[] sss = ss.split("\\^");

            String jiagebizhong = t.select("label[class=fare-amount]").get(0).text();

            String[] jiages = jiagebizhong.split(" ");

            if (ss.indexOf("^") < 1) {
                LinkedList<Segment> segments = Lists.newLinkedList();
                Segment segment = new Segment();
                segment.setFlightNumber(sss[0].substring(0, 7).replace("~", "").replace(" ", ""));// 航班号集合
                segment.setCarrier(sss[0].substring(0, 2));// 航班号
                segment.setDepAirport(sss[0].substring(11,14));
                segment.setDepTime(DateTime.parse(sss[0].substring(sss[0].indexOf(dep) + 4, sss[0].indexOf(dep) + 20), DateTimeFormat.forPattern("MM/dd/yyyy HH:mm")).toString("yyyyMMddHHmm"));
                segment.setArrAirport(sss[0].substring(32,35));
                segment.setArrTime(DateTime.parse(sss[0].substring(sss[0].indexOf(arr) + 4, sss[0].indexOf(arr) + 20), DateTimeFormat.forPattern("MM/dd/yyyy HH:mm")).toString("yyyyMMddHHmm"));
                segment.setCodeShare(false);
                segment.setStopCities("");// 空
                segment.setCabin("Y");// Y仓位
                // segment.setAircraftCode(carrier);// 机型
                segment.setCabinClass(1);
                segments.add(segment);

                Rule rl = new Rule();
                rl.setHasRefund(0);
                rl.setRefund("一旦出票，不允许退票，包括已经代为收取的机场建设费、燃油附加费和相关税费也不可退");
                rl.setPartRefund(0);
                rl.setPartRefundPrice(0);
                rl.setHasEndorse(0);
                rl.setEndorse("请咨询旺旺客服");
                rl.setPartEndorse(0);
                rl.setPartEndorsePrice(0);
                rl.setEndorsement(0);
                rl.setHasBaggage(0);
                rl.setBaggage("廉价航空公司无免费托运行李额，添加托运行李额请联系旺旺客服");
                rl.setHasNoShow(0);
                rl.setNoShowLimitTime(0);
                rl.setPenalty(0);
                rl.setSpecialNoShow(3);
                rl.setOther("");

                Routing routing = new Routing();
                routing.setAdultPrice(Double.parseDouble(jiages[1].replace(",", "")));
                routing.setAdultTax(0);// 没有抓所以0
                routing.setAdultTaxType(0);
                routing.setApplyType(0);
                routing.setChildPrice(routing.getAdultPrice());
                routing.setChildTax(routing.getAdultTax());
                routing.setChildTaxType(routing.getAdultTaxType());
                routing.setData("5J_" + UUID.randomUUID().toString());
                routing.setCurrency(jiages[0]);
                routing.setFromSegments(segments);
                routing.setNationality("");
                routing.setNationalityType(0);
                routing.setPriceType(0);// 票价类型 成人 1
                routing.setRetSegments(new ArrayList<Segment>());
                routing.setRule(rl);
                routing.setSuitAge("");
                routing.setTicketInvoiceType(0);
                rts.add(routing);
            } else {
                LinkedList<Segment> segments = Lists.newLinkedList();
                Segment segment = new Segment();
                segment.setFlightNumber(sss[0].substring(0, 7).replace("~", "").replace(" ", ""));// 航班号集合
                segment.setCarrier(sss[0].substring(0, 2));// 航班号
                segment.setDepAirport(dep);
                segment.setDepTime(DateTime.parse(sss[0].substring(sss[0].indexOf(dep) + 4, sss[0].indexOf(dep) + 20), DateTimeFormat.forPattern("MM/dd/yyyy HH:mm")).toString("yyyyMMddHHmm"));
                segment.setArrAirport(sss[0].substring(sss[0].indexOf(dep) + 21, sss[0].indexOf(dep) + 24));
                segment.setArrTime(DateTime.parse(sss[0].substring(sss[0].indexOf(dep) + 25, sss[0].indexOf(dep) + 41), DateTimeFormat.forPattern("MM/dd/yyyy HH:mm")).toString("yyyyMMddHHmm"));
                segment.setCodeShare(false);
                segment.setStopCities("");// 空
                segment.setCabin("Y");// Y仓位
                // segment.setAircraftCode(carrier);// 机型
                segment.setCabinClass(1);
                segments.add(segment);
                Segment segment2 = new Segment();
                segment2.setFlightNumber(sss[1].substring(0, 7).replace("~", "").replace(" ", ""));// 航班号集合
                segment2.setCarrier(sss[1].substring(0, 2));// 航班号
                segment2.setDepTime(DateTime.parse(sss[1].substring(sss[1].indexOf(arr) - 17, sss[1].indexOf(arr) - 1), DateTimeFormat.forPattern("MM/dd/yyyy HH:mm")).toString("yyyyMMddHHmm"));
                segment2.setDepAirport(sss[1].substring(sss[1].indexOf(arr) - 21, sss[1].indexOf(arr) - 18));
//                segment2.setDepAirport(sss[0].substring(sss[0].indexOf(dep) + 21, sss[0].indexOf(dep) + 24));
                segment2.setArrAirport(arr);
                segment2.setArrTime(DateTime.parse(sss[1].substring(sss[1].length() - 17, sss[1].length() - 1), DateTimeFormat.forPattern("MM/dd/yyyy HH:mm")).toString("yyyyMMddHHmm"));
                segment2.setCodeShare(false);
                segment2.setStopCities("");// 空
                segment2.setCabin("Y");// Y仓位
                // segment2.setAircraftCode();// 机型
                segment2.setCabinClass(1);
                segments.add(segment2);

                Rule rl = new Rule();
                rl.setHasRefund(0);
                rl.setRefund("一旦出票，不允许退票，包括已经代为收取的机场建设费、燃油附加费和相关税费也不可退");
                rl.setPartRefund(0);
                rl.setPartRefundPrice(0);
                rl.setHasEndorse(0);
                rl.setEndorse("请咨询旺旺客服");
                rl.setPartEndorse(0);
                rl.setPartEndorsePrice(0);
                rl.setEndorsement(0);
                rl.setHasBaggage(0);
                rl.setBaggage("廉价航空公司无免费托运行李额，添加托运行李额请联系旺旺客服");
                rl.setHasNoShow(0);
                rl.setNoShowLimitTime(0);
                rl.setPenalty(0);
                rl.setSpecialNoShow(3);
                rl.setOther("");

                Routing routing = new Routing();
                routing.setAdultPrice(Double.parseDouble(jiages[1].replace(",", "")));
                routing.setAdultTax(0);// 没有抓所以0
                routing.setAdultTaxType(0);
                routing.setApplyType(0);
                routing.setChildPrice(routing.getAdultPrice());
                routing.setChildTax(routing.getAdultTax());
                routing.setChildTaxType(routing.getAdultTaxType());
                routing.setData("5J_" + UUID.randomUUID().toString());
                routing.setCurrency(jiages[0]);
                routing.setFromSegments(segments);
                routing.setNationality("");
                routing.setNationalityType(0);
                routing.setPriceType(0);// 票价类型 成人 1
                routing.setRetSegments(new ArrayList<Segment>());
                routing.setRule(rl);
                routing.setSuitAge("");
                routing.setTicketInvoiceType(0);
                rts.add(routing);
            }
        }
        CacheDataObject cdo = new CacheDataObject();
        ReturnObject ro = new ReturnObject();
        ro.setRoutings(rts);
        ro.setMsg("OK");
        ro.setStatus(0);
        cdo.setDbFlag(0);
        cdo.setFlag("true");
        cdo.setReturnObject(ro);
        cdo.setTimeNow(DateTime.now().toString());
        return cdo;
    }

    public static void main(String[] args) {
        HttpClientSystem client = new HttpClientSystem();
        _5J j = new _5J();
//        j._Zh5JSearch(client, "SIN", "MNL", "2018-04-19", "1");
        j._5JSearch(client, "SIN", "MNL", "2018-09-04", "1");
    }

    private CacheDataObject _Zh5JSearch(HttpClientSystem client, String dep, String arr, String time, String count) {
        HttpGet get = new HttpGet();
        get.setURI(URI.create("https://beta.cebupacificair.com/Flight/Select?o1=" + dep + "&d1=" + arr + "&o2=&d2=&dd1=" + time + "&ADT=" + count + "&CHD=0&INF=0&inl=0&pos=cebu.cn&culture=zh-cn"));
        get.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        get.setHeader("Connection", "keep-alive");
        get.setHeader("Upgrade-Insecure-Requests", "1");
        get.setHeader("user-agent", ParamsUtil.USER_AGENT_CHROME);
        String string = client.get(get);
        if (string == null)
            return null;

        LinkedList<Routing> rts = Lists.newLinkedList();

        Document document = Jsoup.parse(string);

        Elements tbodys = document.getElementsByTag("tbody");
        if (tbodys == null || tbodys.size() <= 1)
            return null;
        Element tbody = tbodys.get(1);

        Elements trs = tbody.children();// 所有航线
        for (Element t : trs) {
            if (t.text().contains("Sorry,")) {
                CacheDataObject cdo = new CacheDataObject();
                ReturnObject ro = new ReturnObject();
                ro.setRoutings(rts);
                ro.setStatus(0);
                ro.setMsg("sorry the day no data");
                cdo.setDbFlag(0);
                cdo.setFlag("true");
                cdo.setReturnObject(ro);
                cdo.setTimeNow(DateTime.now().toString());
                return cdo;
            }

            if (!t.attr("class").equals(""))
                continue;

            Element input = t.getElementsByTag("input").get(0);

            String value = input.attr("value");

            String ss = value.split("\\|")[1];
            String[] sss = ss.split("\\^");

            String jiagebizhong = t.select("label[class=fare-amount]").get(0).text();

            String[] jiages = jiagebizhong.split(" ");

            if (ss.indexOf("^") < 1) {
                LinkedList<Segment> segments = Lists.newLinkedList();
                Segment segment = new Segment();
                segment.setFlightNumber(sss[0].substring(0, 7).replace("~", "").replace(" ", ""));// 航班号集合
                segment.setCarrier(sss[0].substring(0, 2));// 航班号
                segment.setDepAirport(dep);
                segment.setDepTime(DateTime.parse(sss[0].substring(sss[0].indexOf(dep) + 4, sss[0].indexOf(dep) + 20), DateTimeFormat.forPattern("MM/dd/yyyy HH:mm")).toString("yyyyMMddHHmm"));
                segment.setArrAirport(arr);
                segment.setArrTime(DateTime.parse(sss[0].substring(sss[0].indexOf(arr) + 4, sss[0].indexOf(arr) + 20), DateTimeFormat.forPattern("MM/dd/yyyy HH:mm")).toString("yyyyMMddHHmm"));
                segment.setCodeShare(false);
                segment.setStopCities("");// 空
                segment.setCabin("Y");// Y仓位
                // segment.setAircraftCode(carrier);// 机型
                segment.setCabinClass(1);
                segments.add(segment);

                Rule rl = new Rule();
                rl.setHasRefund(0);
                rl.setRefund("一旦出票，不允许退票，包括已经代为收取的机场建设费、燃油附加费和相关税费也不可退");
                rl.setPartRefund(0);
                rl.setPartRefundPrice(0);
                rl.setHasEndorse(0);
                rl.setEndorse("请咨询旺旺客服");
                rl.setPartEndorse(0);
                rl.setPartEndorsePrice(0);
                rl.setEndorsement(0);
                rl.setHasBaggage(0);
                rl.setBaggage("廉价航空公司无免费托运行李额，添加托运行李额请联系旺旺客服");
                rl.setHasNoShow(0);
                rl.setNoShowLimitTime(0);
                rl.setPenalty(0);
                rl.setSpecialNoShow(3);
                rl.setOther("");

                Routing routing = new Routing();
                routing.setAdultPrice(Double.parseDouble(jiages[1].replace(",", "")));
                routing.setAdultTax(0);// 没有抓所以0
                routing.setAdultTaxType(0);
                routing.setApplyType(0);
                routing.setChildPrice(routing.getAdultPrice());
                routing.setChildTax(routing.getAdultTax());
                routing.setChildTaxType(routing.getAdultTaxType());
                routing.setData("5J_" + UUID.randomUUID().toString());
                routing.setCurrency(jiages[0]);
                routing.setFromSegments(segments);
                routing.setNationality("");
                routing.setNationalityType(0);
                routing.setPriceType(0);// 票价类型 成人 1
                routing.setRetSegments(new ArrayList<Segment>());
                routing.setRule(rl);
                routing.setSuitAge("");
                routing.setTicketInvoiceType(0);
                rts.add(routing);
            } else {
                LinkedList<Segment> segments = Lists.newLinkedList();
                Segment segment = new Segment();
                segment.setFlightNumber(sss[0].substring(0, 7).replace("~", "").replace(" ", ""));// 航班号集合
                segment.setCarrier(sss[0].substring(0, 2));// 航班号
                segment.setDepAirport(dep);
                segment.setDepTime(DateTime.parse(sss[0].substring(sss[0].indexOf(dep) + 4, sss[0].indexOf(dep) + 20), DateTimeFormat.forPattern("MM/dd/yyyy HH:mm")).toString("yyyyMMddHHmm"));
                segment.setArrAirport(sss[0].substring(sss[0].indexOf(dep) + 21, sss[0].indexOf(dep) + 24));
                segment.setArrTime(DateTime.parse(sss[0].substring(sss[0].indexOf(dep) + 25, sss[0].indexOf(dep) + 41), DateTimeFormat.forPattern("MM/dd/yyyy HH:mm")).toString("yyyyMMddHHmm"));
                segment.setCodeShare(false);
                segment.setStopCities("");// 空
                segment.setCabin("Y");// Y仓位
                // segment.setAircraftCode(carrier);// 机型
                segment.setCabinClass(1);
                segments.add(segment);
                Segment segment2 = new Segment();
                segment2.setFlightNumber(sss[1].substring(0, 7).replace("~", "").replace(" ", ""));// 航班号集合
                segment2.setCarrier(sss[1].substring(0, 2));// 航班号
                segment2.setDepTime(DateTime.parse(sss[1].substring(sss[1].indexOf(arr) - 17, sss[1].indexOf(arr) - 1), DateTimeFormat.forPattern("MM/dd/yyyy HH:mm")).toString("yyyyMMddHHmm"));
                segment2.setDepAirport(sss[1].substring(sss[1].indexOf(arr) - 21, sss[1].indexOf(arr) - 18));
                segment2.setArrAirport(arr);
                segment2.setArrTime(DateTime.parse(sss[1].substring(sss[1].length() - 17, sss[1].length() - 1), DateTimeFormat.forPattern("MM/dd/yyyy HH:mm")).toString("yyyyMMddHHmm"));
                segment2.setCodeShare(false);
                segment2.setStopCities("");// 空
                segment2.setCabin("Y");// Y仓位
                // segment2.setAircraftCode();// 机型
                segment2.setCabinClass(1);
                segments.add(segment2);

                Rule rl = new Rule();
                rl.setHasRefund(0);
                rl.setRefund("一旦出票，不允许退票，包括已经代为收取的机场建设费、燃油附加费和相关税费也不可退");
                rl.setPartRefund(0);
                rl.setPartRefundPrice(0);
                rl.setHasEndorse(0);
                rl.setEndorse("请咨询旺旺客服");
                rl.setPartEndorse(0);
                rl.setPartEndorsePrice(0);
                rl.setEndorsement(0);
                rl.setHasBaggage(0);
                rl.setBaggage("廉价航空公司无免费托运行李额，添加托运行李额请联系旺旺客服");
                rl.setHasNoShow(0);
                rl.setNoShowLimitTime(0);
                rl.setPenalty(0);
                rl.setSpecialNoShow(3);
                rl.setOther("");

                Routing routing = new Routing();
                routing.setAdultPrice(Double.parseDouble(jiages[1].replace(",", "")));
                routing.setAdultTax(0);// 没有抓所以0
                routing.setAdultTaxType(0);
                routing.setApplyType(0);
                routing.setChildPrice(routing.getAdultPrice());
                routing.setChildTax(routing.getAdultTax());
                routing.setChildTaxType(routing.getAdultTaxType());
                routing.setData("5J_" + UUID.randomUUID().toString());
                routing.setCurrency(jiages[0]);
                routing.setFromSegments(segments);
                routing.setNationality("");
                routing.setNationalityType(0);
                routing.setPriceType(0);// 票价类型 成人 1
                routing.setRetSegments(new ArrayList<Segment>());
                routing.setRule(rl);
                routing.setSuitAge("");
                routing.setTicketInvoiceType(0);
                rts.add(routing);
            }
        }
        CacheDataObject cdo = new CacheDataObject();
        ReturnObject ro = new ReturnObject();
        ro.setRoutings(rts);
        ro.setMsg("OK");
        ro.setStatus(0);
        cdo.setDbFlag(0);
        cdo.setFlag("true");
        cdo.setReturnObject(ro);
        cdo.setTimeNow(DateTime.now().toString());
        return cdo;
    }
}
